<template>
  <div class="app-container purchasewarehouseorder">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.startTime"
        class="filter-item"
        default-time="00:00:00"
        value-format="timestamp"
        placeholder="选择开始日期"
        style="width: 140px"
        type="datetime"
      />
      -
      <el-date-picker
        v-model="listQuery.endTime"
        class="filter-item"
        default-time="23:59:59"
        value-format="timestamp"
        placeholder="选择结束日期"
        style="width: 140px"
        type="datetime"
      />
      <el-input
        v-model="listQuery.lossCheckNo"
        class="filter-item"
        clearable
        placeholder="输入单号"
        style="width: 140px;"
      />
      <el-input
        v-model="listQuery.skuSearch"
        clearable
        class="filter-item"
        style="width: 140px;"
        placeholder="输入条码/商品名称"
      />
      <el-select
        v-model="listQuery.lossCheckState"
        class="filter-item"
        clearable
        placeholder="请选择状态"
        style="width: 120px">
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value"/>
      </el-select>
      <el-button
        v-permission="['warehouseloss:warehouseloss:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找
      </el-button>
      <el-button
        v-permission="['warehouseloss:warehouseloss:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="skuSummary"
      >导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column align="center" label="损耗单号" width="150px">
        <template slot-scope="scope">
          <el-link :underline="false" type="primary" @click="handleDetail(scope.row)">{{ scope.row.lossCheckNo }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型">
        <template slot-scope="scope">{{ scope.row.lossType | formatType }}</template>
      </el-table-column>
      <el-table-column align="center" label="制单时间">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatGmt }}</template>
      </el-table-column>
      <el-table-column prop="lossCheckCount" align="center" label="损耗数量"/>
      <el-table-column align="center" label="损耗金额" prop="lossCheckAmount">
        <template slot-scope="scope"><el-col>{{ scope.row.lossCheckAmount/ 100 }}</el-col></template>
      </el-table-column>
      <el-table-column prop="lossCheckUser" align="center" label="操作人"/>
      <el-table-column prop="lossCheckConfirmUsername" align="center" label="确认人"/>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if=" scope.row.lossCheckState === 0" type="danger">待确认</el-tag>
          <el-tag v-if=" scope.row.lossCheckState === 1">已确认</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="['warehouseloss:warehouseloss:confirm']"
            v-if="scope.row.lossCheckState!='1'"
            type="primary"
            size="mini"
            @click="handleConfirm(scope.row)"
          >确认
          </el-button>
          <el-button
            v-permission="['warehouseloss:warehouseloss:update']"
            v-if="scope.row.lossCheckState!='1'"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['warehouseloss:warehouseloss:detail']"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
          >查看
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handlePrint(scope.row)"
          >打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 确认对话框 -->
    <el-dialog
      v-loading="confirmFormLoading"
      :visible.sync="confirmDialogVisible"
      title="系统提示"
      center
      width="30%">
      <span style="font-weight: 400;">确认之后，仓库数量会更新为损耗之后的数量!<br><br>是否确认？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLoss()">确认</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :width="optDiaLogWidth" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
      >
        <el-form-item v-if="hidden" prop="id"/>
        <el-form-item prop="warehouseId">
          <label slot="label">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库</label>
          <el-select v-model="dataForm.warehouseId" placeholder="请选择" @change="ifCanSelSpu">
            <el-option v-for="(key, index) in warehouseList" :key="index" :label="key.warehouseName" :value="key.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="单据备注" prop="lossCheckInfo">
          <el-col :span="12">
            <el-input v-model="dataForm.lossCheckInfo" rows="3" clearable placeholder="" type="textarea"/>
          </el-col>
        </el-form-item>
        <el-form-item>
          <label slot="label">类&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型</label>
          <el-radio-group v-model="dataForm.lossType">
            <el-radio :label="0">普通</el-radio>
            <el-radio :label="1">品鉴</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="损耗商品" prop="warehouseLossGoodsDTOS">
          <el-col :span="4"><span>已选择({{ selectSpuList.length>0?selectSpuList.length :'0' }})件商品</span></el-col>
          <el-col :span="10">
            <el-button
              :disabled="dataForm.warehouseIsSelected"
              size="mini"
              type="primary"
              @click="handleSpuAdd(dataForm.warehouseId)">选择商品
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="商品详情">
          <el-table
            :data="selectSpuList"
            border
            fit
            highlight-current-row
            size="small"
            height="260"
            style="white-space: pre-line">
            <el-table-column v-if="hidden" align="center" label="id" prop="goodsId"/>
            <el-table-column v-if="hidden" align="center" label="skuId" prop="skuId"/>
            <el-table-column v-if="hidden" align="center" label="spuId" prop="spuId"/>
            <el-table-column align="center" label="商品" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40"></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.goodsName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="条形码" prop="barCode"/>
            <el-table-column align="center" label="单位" prop="unit" width="60px"/>
            <el-table-column align="center" label="总库存" prop="warehouseSkuNum"/>
            <el-table-column align="center" label="损耗数量" width="120px">
              <template slot-scope="scope">
                <el-form ref="scope.row" status-icon>
                  <el-form-item>
                    <el-input v-model="scope.row.lossCheckGoodsNum" placeholder=""/>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="剩余数量" prop="lossCheckAftGoodsNum" width="80px">
              <template slot-scope="scope">
                <el-form ref="scope.row">
                  <el-form-item prop="lossCheckAftGoodsNum">
                    <el-col
                      v-if="scope.row.warehouseSkuNum && scope.row.lossCheckGoodsNum"
                      v-model="scope.row.lossCheckAftGoodsNum">{{ (scope.row.warehouseSkuNum -
                      scope.row.lossCheckGoodsNum).toFixed(2) }}
                    </el-col>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="成本价">
              <template slot-scope="scope">
                <el-col>{{ (scope.row.averPrice).toFixed(2) }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="损耗金额" prop="lossCheckAmount">
              <template slot-scope="scope">
                <el-col v-if="scope.row.averPrice && scope.row.warehouseSkuNum && scope.row.lossCheckGoodsNum">
                  <span>{{ (scope.row.averPrice * scope.row.lossCheckGoodsNum).toFixed(2) }}</span>
                </el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="50px">
              <template slot-scope="scope">
                <el-link :underline="false" @click="removeSpu(scope.row.skuId)"><span style="color: red;">移除</span>
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="损耗总额" prop="totalPrice">
          <el-col :style="(selSpuListTotalPrice <0 ?'color:red':'')">{{ selSpuListTotalPrice }}</el-col>
        </el-form-item>
        <el-form-item label="损耗总数" prop="total">
          <el-col :style="(selSpuListTotal <0 ?'color:red':'')">{{ selSpuListTotal }}</el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog :visible.sync="spuDialogFormVisible" :custom-class="spuDialogClass" title="商品选择">
      <template>
        <div class="app-container" style="padding-bottom: 0;padding-top: 0;">
          <!-- 查询和其他操作 -->
          <div class="filter-container">
            <el-cascader
              :options="categoryOptions"
              :props="{ checkStrictly: true }"
              class="filter-item"
              clearable
              filterable
              placeholder="请选择类目"
              style="width: 200px;"
              @change="handleCategoryOption"/>
            <el-input
              v-model="listSpuQuery.search"
              class="filter-item"
              clearable
              placeholder="输入名称或条码"
              style="width: 200px;"
            />
            <el-button
              class="filter-item"
              icon="el-icon-search"
              type="primary"
              @click="handleSpuFilter"
            >查找
            </el-button>
          </div>

          <!-- 查询结果 -->
          <el-table
            v-loading="listSpuLoading"
            ref="spuTable"
            :data="spuList"
            :row-key="getRowKey"
            border
            element-loading-text="正在查询中。。。"
            fit
            highlight-current-row
            size="small"
            style="white-space: pre-line"
            @selection-change="selectChange"
          >
            <el-table-column
              :reserve-selection="true"
              :selectable="ifCanSelectSpu"
              align="center"
              type="selection"
              width="55"/>
            <el-table-column v-if="hidden" prop="skuId"/>
            <el-table-column v-if="hidden" prop="spuId"/>
            <el-table-column align="center" label="商品名称" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40"></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.goodsName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" prop="unit"/>
            <el-table-column align="center" label="条形码" prop="barCode"/>
            <el-table-column align="center" label="可用库存" prop="warehouseSkuNum"/>
            <el-table-column align="center" label="成本价" width="60px">
              <template slot-scope="scope">
                <el-col>{{ (scope.row.averPrice).toFixed(2) }}</el-col>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="spuListTotal>0"
            :limit.sync="listSpuQuery.limit"
            :page.sync="listSpuQuery.pageNo"
            :total="spuListTotal"
            :pager-count="5"
            layout="prev, pager, next"
            style="padding-bottom: 0;padding-top: 0;"
            @pagination="listGoods"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="spuDialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="saveWarehouseSpu">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 打印 -->
    <el-dialog title="打印" :visible.sync="dialogTableVisible" class="printBox">
      <printHtml :outbound="4" :pOrderId="pOrderId" />
    </el-dialog>
  </div>
</template>

<style>
  .el-table .cell {
    white-space: pre-line;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

  .spuDialogClass .el-dialog__body {
    padding-bottom: 0;
    padding-top: 10px;
  }

  .spuDialogClass .el-dialog__footer {
    padding-top: 0;
  }
</style>

<script>
import { confirm, create, listLoss, update } from '@/api/warehouseloss'
import { formatDateAndTime } from '@/filters'
import { timestampToTime } from '@/utils/dateTimeUtil'
import { listWareHousesByPara, exportSkuSummary } from '@/api/warehouse'
import { listWarehouseSkusByPara, querySkusByWarehouseId } from '@/api/warehouselossgoods'
import { categorySecondLevelTree, categoryTree } from '@/api/category'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const extraStatusMap = {
  '0': '待确认',
  '1': '已确认'
}
export default {
  name: 'WarehouseLoss',
  components: { Pagination },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return ''
      }
      return formatDateAndTime(time)
    },
    formatOrderState(state) {
      switch (state) {
        case 0 :
          return '待确认'
        case 1 :
          return '已确认'
        default :
          return ''
      }
    },
    formatType(type) {
      switch (type) {
        case 0 :
          return '普通'
        case 1 :
          return '品鉴'
        default :
          return ''
      }
    }
  },
  data() {
    return {
      dialogTableVisible: false,
      pOrderId: "", //844
      extraStatusMap,
      statusMap: [{ value: 0, name: '待确认' }, { value: 1, name: '已确认' }],
      list: undefined,
      total: 0,
      warehouseList: [],
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        lossCheckNo: undefined,
        skuSearch: undefined
      },
      listSpuQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        lossCheckState: undefined,
        warehouseId: undefined,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        lossCheckId: undefined
      },
      hidden: false,
      selectSpuList: [],
      selectGoodList: [],
      spuListTotal: 0,
      options: [],
      dataForm: {
        id: undefined
      },
      dialogFormVisible: false,
      spuDialogFormVisible: false,
      listSpuLoading: true,
      spuList: [],
      categoryOptions: [],
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      confirmDialogVisible: false,
      confirmFormLoading: true,
      rules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ]
      },
      optDiaLogWidth: '80%',
      spuDialogClass: 'spuDialogClass',
      goodNumValid: true
    }
  },
  computed: {
    selSpuListTotal: function() {
      if (this.selectSpuList.length) {
        let total = 0
        for (let i = 0; i < this.selectSpuList.length; i++) {
          if (this.selectSpuList[i].warehouseSkuNum && this.selectSpuList[i].lossCheckGoodsNum) {
            total += (parseFloat(this.selectSpuList[i].lossCheckGoodsNum))
          }
        }
        return total.toFixed(3)
      }
    },
    selSpuListTotalPrice: function() {
      let totalPrice = 0
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].averPrice && this.selectSpuList[i].warehouseSkuNum && this.selectSpuList[i].lossCheckGoodsNum) {
          totalPrice += this.selectSpuList[i].averPrice * (parseFloat(this.selectSpuList[i].lossCheckGoodsNum))
        }
      }
      return totalPrice.toFixed(2)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    listWareHousesByPara() {
      listWareHousesByPara({ status: 1 })
        .then(response => {
          this.warehouseList = response.data.data
        })
        .catch(() => {
          this.warehouseList = []
        })
    },
    getList() {
      this.listLoading = true
      listLoss(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        this.listQuery.insertStartTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        this.listQuery.insertEndTime = timestampToTime(endTimeLong)
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        warehouseIsSelected: true,
        lossType: 0
      }
      this.selectSpuList = []
      this.spuList = []
    },
    handleCreate() {
      this.resetForm()
      this.listWareHousesByPara()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.goodNumValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let goodNumValid = true
          for (let i = 0; i < selectSpuList.length; i++) {
            if (!selectSpuList[i].lossCheckGoodsNum) {
              isHasEmptyValue = true
              break
            }
            console.log(selectSpuList[i].lossCheckGoodsNum)
            const goodsNum = new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].lossCheckGoodsNum)
            if (!goodsNum) {
              goodNumValid = false
              break
            } else {
              goodNumValid = true
              if (selectSpuList[i].lossCheckGoodsNum && selectSpuList[i].warehouseSkuNum < selectSpuList[i].lossCheckGoodsNum) {
                this.$notify({
                  title: '提示',
                  message: '数量不能大于可用库存',
                  type: 'warning'
                })
                break
              }
            }
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: '请核对数量'
            })
          } else if (!goodNumValid) {
            this.$notify({
              title: '提示',
              message: '盘点数量请填写整数或者两位小数',
              type: 'warning'
            })
          } else {
            this.dataForm.warehouseLossGoodsDTOS = this.selectSpuList
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            create(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleUpdate(row) {
      this.listSpuQuery.warehouseId = row.warehouseId
      this.listWareHousesByPara()
      this.listSpuQuery.lossCheckId = row.id
      this.listWarehouseGoods()
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.goodNumValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let goodNumValid = true
          for (let i = 0; i < selectSpuList.length; i++) {
            if (!selectSpuList[i].lossCheckGoodsNum) {
              isHasEmptyValue = true
              break
            }
            const goodsNum = new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].lossCheckGoodsNum)
            if (!goodsNum) {
              goodNumValid = false
              break
            } else {
              goodNumValid = true
              if (selectSpuList[i].lossCheckGoodsNum && selectSpuList[i].warehouseSkuNum < selectSpuList[i].lossCheckGoodsNum) {
                this.$notify({
                  title: '提示',
                  message: '数量不能大于可用库存',
                  type: 'warning'
                })
                break
                // this.$set(row, 'lossCheckGoodsNum', '')
              }
            }
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: '请核对数量'
            })
          } else if (!goodNumValid) {
            this.$notify({
              title: '提示',
              message: '盘点数量请填写整数或者两位小数',
              type: 'warning'
            })
          } else {
            this.dataForm.warehouseLossGoodsDTOS = this.selectSpuList
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            update(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleSpuFilter() {
      this.listSpuQuery.pageNo = 1
      this.listGoods()
    },
    ifCanSelSpu() {
      this.dataForm.warehouseIsSelected = true
      if (this.dataForm.warehouseId) {
        this.dataForm.warehouseIsSelected = false
      }
    },
    handleSpuAdd(warehouseId) {
      this.spuDialogFormVisible = true
      this.listSpuQuery.warehouseId = warehouseId
      this.categoryOptions = []
      this.categorySecondLevelTree()
      this.refreshCategoryOptions()
      this.listGoods()
      if (this.$refs['spuTable']) {
        this.$refs['spuTable'].clearSelection()
        if (this.selectSpuList) {
          this.selectSpuList.forEach(row => {
            this.$refs['spuTable'].toggleRowSelection(row, true)
          })
        }
      }
    },
    listWarehouseGoods() {
      this.listSpuQuery.status = 1
      listWarehouseSkusByPara(this.listSpuQuery)
        .then(response => {
          this.selectSpuList = response.data.data
        })
        .catch(() => {
          this.selectSpuList = []
        })
    },
    listGoods() {
      this.listSpuQuery.status = 1
      this.listSpuLoading = true
      querySkusByWarehouseId(this.listSpuQuery)
        .then(response => {
          this.spuList = response.data.data.items
          this.spuListTotal = response.data.data.total
          this.listSpuLoading = false
        })
        .catch(() => {
          this.spuList = []
          this.listSpuLoading = false
        })
    },
    saveWarehouseSpu() {
      const selection = this.selectGoodList
      for (let i = 0; i < this.selectSpuList.length; i++) {
        for (let j = 0; j < selection.length; j++) {
          if (this.selectSpuList[i].skuId && this.selectSpuList[i].skuId === selection[j].skuId && this.selectSpuList[i].stockCheckAftGoodsNum) {
            this.$set(selection[j], 'stockCheckAftGoodsNum', this.selectSpuList[i].stockCheckAftGoodsNum)
            break
          }
        }
      }
      this.spuDialogFormVisible = false
      this.selectSpuList = selection
    },
    removeSpu(skuId) {
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].skuId === skuId) {
          this.selectSpuList.splice(i, 1)
          break
        }
      }
    },
    categorySecondLevelTree() {
      categorySecondLevelTree()
        .then(response => {
          this.categoryList = response.data.data
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    handleCategoryOption(e) {
      if (e !== undefined) {
        const tag = e[e.length - 1]
        this.listSpuQuery.skuIds = tag // 回调指定分类
      } else {
        this.listSpuQuery.skuIds = undefined
      }
    },
    refreshCategoryOptions() {
      if (this.categoryOptions.length === 0) {
        categoryTree().then(response => {
          this.categoryOptions = response.data.data
        })
      }
    },
    getRowKey(row) {
      return row.skuId
    },
    ifCanSelectSpu(row, index) {
      return row.warehouseSkuNum > 0
    },
    selectChange(selection) {
      this.selectGoodList = selection
    },
    handleDetail(row) {
      this.$router.push({ path: '/warehouse/lossDetail?lossCheckId=' + row.id })
    },
    handlePrint(row) {
      // var url = window.location.href.split('#')[0]
      // window.open(`${url}#/printdetail?pOrderId=${row.id}&outbound=4`)
      this.dialogTableVisible = true;
      this.pOrderId = row.id;
    },
    handleConfirm(row) {
      this.confirmDialogVisible = true
      this.confirmDataForm = {
        lossCheckState: '1',
        lossCheckId: row.id
      }
    },
    confirmLoss() {
      this.confirmFormLoading = true
      confirm(this.confirmDataForm)
        .then(response => {
          this.confirmFormLoading = false
          this.confirmDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '确认成功'
          })
          this.getList()
        })
        .catch(response => {
          this.confirmFormLoading = false
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    goodsNumLimit(row) {
      const flag = new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(row.lossCheckGoodsNum)
      if (!flag) {
        // this.$notify({
        //   title: '提示',
        //   message: '盘点数量请填写整数',
        //   type: 'warning'
        // })
        this.goodNumValid = false

        // this.$set(row, 'lossCheckGoodsNum', '')
      } else {
        this.goodNumValid = true
        // if (row.lossCheckGoodsNum && row.warehouseSkuNum < row.lossCheckGoodsNum) {
        //   this.$notify({
        //     title: '提示',
        //     message: '数量不能大于可用库存',
        //     type: 'warning'
        //   })
        //   // this.$set(row, 'lossCheckGoodsNum', '')
        // }
      }
    },
    skuSummary() {
      let startTime = ''
      let endTime = ''
      if (!this.listQuery.startTime || !this.listQuery.startTime) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择导出时间范围'
        })
        return
      }
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        startTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        endTime = timestampToTime(endTimeLong)
      }
      exportSkuSummary(startTime, endTime, 0, this.listQuery.lossCheckState, this.extraStatusMap[this.listQuery.lossCheckState], this.listQuery.lossCheckNo, 14, this.listQuery.skuSearch)
    }
  }
}
</script>
